package com.heima.brhavior.service.impl;

import com.heima.brhavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author lo
 */
@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //1.判断参数
        if (userId != null) {
            //使用用户查询
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(
                    Query.query(Criteria.
                            where("entryId").is(userId)
                            .and("type").is(ApBehaviorEntry.Type.USER.getCode())),
                    ApBehaviorEntry.class);
            if (behaviorEntry == null) {
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                //给用户创建一个行为实体
                apBehaviorEntry.setType((short) 1);
                apBehaviorEntry.setEntryId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }
            return behaviorEntry;
        }
        if (equipmentId != null){
            //使用设备id查询
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(
                    Query.query(Criteria
                            .where("entryId").is("equipmentId")
                            .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())),
                    ApBehaviorEntry.class);
            if (apBehaviorEntry == null) {
                ApBehaviorEntry behaviorEntry = new ApBehaviorEntry();
                //给设备id创建行为实体
                behaviorEntry.setType((short)0);
                behaviorEntry.setEntryId(equipmentId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
                return behaviorEntry;
            }
            return apBehaviorEntry;
        }
        return null;
    }
}




